/* Copyright 2009 Palm, Inc.  All rights reserved. */

var CalllogAssistant = Class.create({
	// commands for view menu buttons
    kAllCallsMenuCommand: 'all-calls-tap',
	kMissedCallsMenuCommand: 'missed-calls-tap',
	kClearAllCallsMenuCommand: 'clear-all-cmd',
	kRingtonesMenuCommand: 'ringtones',
	
	initialize: function(type) {
		this.appAssistant = Mojo.Controller.getAppController().assistant;
		this.contacts = this.appAssistant.contacts; 
		this.announcer = this.appAssistant.announcer;
		this.stageController = Mojo.Controller.getAppController().getStageController("PhoneApp");
		this.telListener = this.appAssistant.telephonyEventListener;
		
		this.launchType = (type || "");
		
		this.voicemailBadgeUpdate = this.voicemailBadgeUpdate.bind(this);
		this.callLogListDeleteHandler = this.callLogListDeleteHandler.bindAsEventListener(this);
		this.callLogListTapHandler = this.callLogListTapHandler.bindAsEventListener(this);
		this.displayStatusChangeCallback = this.displayStatusChangeCallback.bind(this);
		this.maybeRefreshLists = this.maybeRefreshLists.bind(this);
		this.onItemRendered = this.onItemRendered.bind(this);
		
		this.onAllCallsTap = this.onAllCallsTap.bind(this);
		this.onMissedCallsTap = this.onMissedCallsTap.bind(this);
		this.onVoicemailClick = this.onVoicemailClick.bind(this);
		this.switchToDialpad = this.switchToDialpad.bind(this);
		
		this.contactNumberCache = $H(); // cache of contact ids to phone numbers for that contact
		this.currentlyOpenDrawer = undefined; // hash of currently open drawer, used to ensure only one is open at a time
    },
	
    setup: function() {
		QDLogger.log( "CalllogAssistant#setup");
				
		this.callLogListWidget = this.controller.get('calllog_list');
		this.callLogListWidgetMissed = this.controller.get('calllog_list_missed');
		this.scroller = this.controller.get('call-log-container');
		
		this.controller.setupWidget('call-log-container', {});
		
	 	// Setup the top (view) menu
		var initalCommand = this.launchType == "missed" ? this.kMissedCallsMenuCommand : this.kAllCallsMenuCommand;
		this.topMenuModel = {
			visible: true,
			items: [{
				label:'All Calls / Missed Calls',
				toggleCmd: initalCommand, 
				items: [
					{label:$L('All calls'), command: this.kAllCallsMenuCommand, width:160},
					{label:$L('Missed calls'), command: this.kMissedCallsMenuCommand, width:160}
				]}
			]
		};
		this.controller.setupWidget(Mojo.Menu.viewMenu, { menuClass: 'no-fade call-log' }, this.topMenuModel);
	 	
	 	this.controller.setupWidget('calllog_list', {
			itemsCallback: this.calllogQuery.bind(this),
	        itemTemplate: 'calllog/listitem',
			dividerTemplate: 'calllog/listdivider', 
			swipeToDelete: true,
			dividerFunction: this.dividerFunc,
			emptyTemplate: 'calllog/nil',                                     
			lookahead: 25,
            renderLimit: 45,
           	scrollThreshold: 690,
			splitInitialRender: true,
			hasNoWidgets: true,
			onItemRendered: this.onItemRendered
        });
		
		this.callLogListWidget.observe(Mojo.Event.listTap, this.callLogListTapHandler);
		this.callLogListWidget.observe(Mojo.Event.listDelete, this.callLogListDeleteHandler);
		
		// OPTIMIZATION: if we're going to launch into missed mode, hide all calls widget now
		if ( this.launchType == "missed" ) {
			this.controller.hideWidgetContainer(this.callLogListWidget.hide());
			this.setupMissedCallWidget(true);
		}
		
		this.controller.setupWidget('rowdrawer', {
			drawerBottomOffset: Mojo.Environment.TOUCHABLE_ROW_HEIGHT
		});
		
		this.controller.get('voicemail_button').observe(Mojo.Event.tap, this.onVoicemailClick);
    	this.controller.get('call_log_button').observe(Mojo.Event.tap, this.switchToDialpad);
		
		var appMenuModel = {
			visible: true,
			items: [
				{label: $L('Clear Call History'), command: this.kClearAllCallsMenuCommand},
				{label: $L('Sounds & Ringtones'), command: this.kRingtonesMenuCommand}
			]
		};
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: false}, appMenuModel);
		
		this.controller.listen(this.stageController.document, Mojo.Event.activate, this.maybeRefreshLists);
		this.telListener.displayStateRegisterCallback(this.displayStatusChangeCallback);
	},
	
	activate: function() {
		if (this.launchType == "missed") {
			this.onMissedCallsTap(true);
		} else {
			this.maybeRefreshLists();
		}
		
		// pushing a scene on this will prevent badge from updating, so query again
		this.voicemailBadgeUpdate(this.telListener.lastVoicemail);
		this.telListener.voicemailBadgeCallback = this.voicemailBadgeUpdate.bind(this);
	},
	
	onItemRendered: function(listWidget, itemModel, itemNode) {
		// this item was open when it was kicked off the list
		if (this.currentlyOpenDrawer
			&& this.currentlyOpenDrawer.model.id === itemModel.id 
			&& this.currentlyOpenDrawer.list === listWidget) {
			
			this.openDrawer(itemNode, itemModel, listWidget);
		}
		
		if ( itemModel.calls.length > 1 ) {
			var callCount = itemNode.querySelector('div[name="count"]');
			callCount.show();
			callCount.querySelector('.call-count-wrapper').innerHTML = itemModel.calls.length;
		}
	},
	
	setupMissedCallWidget: function(dont_instantiate) {
		if ( ! this.missedCallWidgetSetup ) {
			this.missedCallWidgetSetup = true;
			
			this.controller.setupWidget('calllog_list_missed', {
				itemsCallback: this.calllogQueryMissed.bind(this),
	            itemTemplate: 'calllog/listitem',
				dividerTemplate: 'calllog/listdivider',
				swipeToDelete: true,
				dividerFunction: this.dividerFunc,
				emptyTemplate: 'calllog/nil-missed',
				lookahead: 25,
	            renderLimit: 45,
	           	scrollThreshold: 690,
				splitInitialRender: true,
				hasNoWidgets: true,
				onItemRendered: this.onItemRendered
	        });
			
			this.callLogListWidgetMissed.setAttribute('x-mojo-element',"List");
			
			if ( ! dont_instantiate ) {
				this.controller.instantiateChildWidgets(this.callLogListWidgetMissed.parentNode);
			}
			
			this.callLogListWidgetMissed.observe(Mojo.Event.listTap, this.callLogListTapHandler);
			this.callLogListWidgetMissed.observe(Mojo.Event.listDelete, this.callLogListDeleteHandler);
		}
	},
	
	displayStatusChangeCallback: function(payload){
		if (payload.event && payload.event == 'displayOn') {
			this.maybeRefreshLists();
		}
	},
	
	refreshLists: function() {
		CallLogList.logCount('', function(count) {
			this.callLogListWidget.mojo.setLengthAndInvalidate(count);
		}.bind(this));
		
		if ( this.missedCallWidgetSetup ) {
			CallLogList.logCount('missed', function(count) {
				this.callLogListWidgetMissed.mojo.setLengthAndInvalidate(count);
			}.bind(this));
		}
	},
	
	maybeRefreshLists: function() {
		if (CallLogList.hasChanged()) {
			this.refreshLists();
		}
	},
	
	cleanup: function() {
		// in case we add another listener before this runs
		if (this.telListener.voicemailBadgeCallback === this.voicemailBadgeUpdate) {
			this.telListener.voicemailBadgeCallback = undefined;
		}
		
		this.closeDrawer();
		
		this.controller.stopListening(this.controller.document, Mojo.Event.activate, this.maybeRefreshLists);
		this.telListener.displayStateUnregisterCallback(this.displayStatusChangeCallback);
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.back) {
			// manually deal with back; always return to dialpad even if there's
			// no dialpad scene yet created
			QDLogger.log( "CalllogAssistant#handleCommand", "back!");
			this.appAssistant.showDialpad();
			Event.stop(event);
			
		} else if (event.type == Mojo.Event.command) {
			switch (event.command) {
				
				case this.kAllCallsMenuCommand:
          			this.onAllCallsTap();
					break;
					
				case this.kMissedCallsMenuCommand:
          			this.onMissedCallsTap();
					break;
				
				case this.kRingtonesMenuCommand:
					MenuController.showRingtones(this.controller.stageController);
					break;
				case this.kClearAllCallsMenuCommand:
					this.doClearCallLogDialog();
					break;
					
				case Mojo.Menu.prefsCmd:
					MenuController.showPrefs(this.controller.stageController);
					break;
					
				case Mojo.Menu.helpCmd:
					MenuController.showHelp();
					break;
			}
		} else {
			// Enable prefs & help menu items
			if (event.type == Mojo.Event.commandEnable &&
				(event.command == Mojo.Menu.prefsCmd || event.command == Mojo.Menu.helpCmd)) {
				event.stopPropagation();
			}
		}
	},
	
	doClearCallLogDialog: function(messages, errorCode) {
		this.controller.showDialog({
			template: 'clearcalllog/clearcalllog-dialog',
			assistant: new ClearcalllogDialogAssistant(this)
		});
	},

	dividerFunc: function(itemModel) {
		return itemModel.timeSeparator;
	},
    
    switchToDialpad: function() {
       this.appAssistant.showDialpad();
    },
	
    onAllCallsTap: function(force) {
		if (this.type !== "" || force === true) {
			this.type = "";
			this.maybeRefreshLists();
			
			var transition = this.controller.prepareTransition(Mojo.Transition.crossFade, false);
			
			this.controller.hideWidgetContainer(this.callLogListWidgetMissed);
			this.callLogListWidgetMissed.hide();
			
			this.callLogListWidget.show();
			this.controller.showWidgetContainer(this.callLogListWidget);
			
			// partial workaround for NOV-88871: scroll to different place than before to prod it to redraw,
			// otherwise, it shows a white box (the list spacer) at the top
			var newScrollX = this.scroller.mojo.getScrollPosition().top ? 1 : 0;
			this.scroller.mojo.scrollTo(newScrollX,0);
			
			transition.run();
		}
    },
	
    onMissedCallsTap: function(skiptransition) {
        if (this.type !== "missed") {
			this.type = "missed";
			
			this.setupMissedCallWidget();
			this.maybeRefreshLists();
			
			if (skiptransition !== true) {
				var transition = this.controller.prepareTransition(Mojo.Transition.crossFade, false);
			}
			
			// force menu to be correct
			this.topMenuModel.items[0].toggleCmd = this.kMissedCallsMenuCommand;
			this.controller.modelChanged(this.topMenuModel);
			
			this.announcer.announceMissedDashboardClear();
			
			this.controller.hideWidgetContainer(this.callLogListWidget);
			this.callLogListWidget.hide();
			
			this.callLogListWidgetMissed.show();
			this.controller.showWidgetContainer(this.callLogListWidgetMissed);
			
			// partial workaround for NOV-88871: scroll to different place than before to prod it to redraw,
			// otherwise, it shows a white box (the list spacer) at the top
			var newScrollX = this.scroller.mojo.getScrollPosition().top ? 1 : 0;
			this.scroller.mojo.scrollTo(newScrollX,0);
			
			if (transition) {
				transition.run();
			}
		}
    },
    
	handleClear: function() {
		this.onAllCallsTap(true /* force */);
		this.contacts.clearLastDialedNumber();
		this.callLogListWidget.mojo.setLength(0);
		if ( this.missedCallWidgetSetup ) {
			this.callLogListWidgetMissed.mojo.setLength(0);
		}
	},
	
    callLogListDeleteHandler: function(event) {
		var idsToDelete = event.item.calls.pluck('id');
		var thisList = event.target;
		var type = (thisList === this.callLogListWidgetMissed ? 'missed' : '');
				
		var now = function(index, needscleanup) {
			
			// delete manually now so indexes are in sync with the cache
			event.preventDefault();
			
			// this.ignoreRequests is a workaround for NOV-89951
			this.ignoreRequests = true;
			thisList.mojo.noticeRemovedItems(index, 1);
			this.ignoreRequests = false;
			
			// two items will be merged as a result of this deletion
			// needscleanup is to be called when we're ready to merge the items
			if ( needscleanup ) {
				
				// wrapper for model's needscleanup that also updates UI
				var cleanup = function() {
					var itemToUpdate = needscleanup();
					var nodeToRemove = thisList.mojo.getNodeByIndex(index);					
					var onAfterAnimation = function() {
						thisList.mojo.noticeUpdatedItems(index - 1, [itemToUpdate]);
						thisList.mojo.noticeRemovedItems(index, 1);
					}.bind(this);
					
					nodeToRemove.style.overflow = "hidden";
					nodeToRemove.style.minHeight = 0;
					Mojo.Animation.animateStyleWithCSS(nodeToRemove, {property: 'height', timingFunction: 'ease-out', duration: 0.3, to: 0, setToComputed: false}, onAfterAnimation);
				}.bind(this);
				
				// CASE: one of the items that will be merged in update() is
				// currently in Delete Confirmation state, we can't cleanup yet
				if ( this.itemInConfirmDeleteMode(thisList, index - 1)
				 	|| this.itemInConfirmDeleteMode(thisList, index)) {
					
					thisList.observe(Mojo.Event.propertyChange, function(e) {
						// remove event listener
						thisList.stopObserving(Mojo.Event.propertyChange, arguments.callee);
						
						// if was a cancel, we can safely cleanup now
						if ( e.value === false ) {
							cleanup();
						}
					});
					
				// CASE: we can cleanup now
				} else {
					cleanup();
				}
			// other case, always invalidate to make sure other rows weren't deleted
			} else {
				// workaround for NOV-89951
				thisList.mojo.invalidateItems(0);
			}
			
			// workaround for NOV-80424
			if ( this.callLogListWidget.mojo.getLength() === 0 ) {
				this.callLogListWidget.mojo.setLength(0);
			}
			if ( this.missedCallWidgetSetup && this.callLogListWidgetMissed.mojo.getLength() === 0 ) {
				this.callLogListWidgetMissed.mojo.setLength(0);
			}
		}.bind(this, event.index);
		
		var after = function() {
			this.contacts.clearLastDialedNumber();
			
			// always update other list
			if ( type == "missed" ) {
				this.callLogListWidget.mojo.invalidateItems(0);
			} else if ( this.missedCallWidgetSetup ) {
				this.callLogListWidgetMissed.mojo.invalidateItems(0);
			}
		}.bind(this);
		
		CallLogList.deleteEntries(idsToDelete, type, now, after, this.controller);
	},
		
	// returns true if the item node at given index in in the swipe deleted state
	// uses private apis of the listwidget
	itemInConfirmDeleteMode: function(thisList, index) {
		var model = thisList.mojo.getItemByNode(thisList.mojo.getNodeByIndex(index));
		return model && model.deleted === this.controller._mojoListDeleteCookie;
	},
	
    callLogListTapHandler: function(event) {
		var target = event.originalEvent.target, model = event.item, thelist = event.target;
		var list_element, was_closed;
		
		//Mojo.Log.info("list tap model: %j, target: %j",model,target.title)
		
		// CASE: tapped avatar, disclose/hide drawer
		if ( target.title == "contact_details" ) {
			list_element = Mojo.View.findParent(function(node) { return node.hasClassName('palm-row'); }, target, thelist);
			was_closed = ! model.open;
			
			this.closeDrawer();
			
			// this drawer was previously closed or non-existant, now open it
			if ( was_closed ) {
				this.openDrawer(list_element, model, thelist);
				this.controller.modelChanged(model); // animate open
			}
		}
		// CASE: make call
		else if ( ! model.disabled ) {
			this.dialNumber(model.number, model.contactId, model.displayLabel);
		}
    },
	
	dialNumber: function(number, contactId, label) {
		QDLogger.log( "Call Log Dialing: ", "number: " , number, contactId, label);
		
		if (this.isValidDialKey(number)) {
			// if we have a valid contact id stored, dial with that to skip reverse lookup
			var contact;
			if (contactId && contactId != -1) {
				contact = {
					id: contactId,
					label: label
				};
			}
			
			var type = this.type != "missed" ? "" : this.type;			
			this.appAssistant.launchDial(number, type, contact);
		}
	},
	
	addDrawerToItem: function(itemNode, itemModel) {		
		// Workaround for NOV-90262: always recreate drawer
		var existingDrawer = itemNode.querySelector('div[name="rowdrawer"]');
		if ( existingDrawer ) {
			existingDrawer.remove();
		}
		
		// a valid number is dial-able and not in our carrierbook. Invalid numbers can't
		// be added to the address book and no SMS button is displayed for them
		var is_valid = this.contacts.isNumberValid(itemModel.number)
				&& Mojo.Controller.getAppController().assistant.contacts.carrierBook[itemModel.number] === undefined;
		
		// Call details
		var nameNode = itemNode.querySelector('div[name="display-name"]');
		var call_details_model = {
			listElements: Mojo.View.render({template: 'calllog/listitem_details_item', collection: itemModel.calls}),
			displayName: itemModel.displayName,
			displayNameClass: nameNode.scrollWidth > nameNode.offsetWidth ? "" : "hidden" // only show if name truncated above
		};
		var call_details = Mojo.View.render({template: 'calllog/listitem_details', object: call_details_model});
		
		// View contact entry
		var view_contact = "", label, template_model;
		if ( is_valid ) {
			label = itemModel.contactId == -1 ? $L("Add to Contacts") : $L("View Contact");
			template_model = {
				contactId: itemModel.contactId,
				number: itemModel.number,
				label: label
			};
			view_contact = Mojo.View.render({template: 'calllog/listitem_contact', object: template_model});
		}
		
		var element = Mojo.View.convertToNode('<div name="rowdrawer" class="calllogdetails" x-mojo-element="Drawer"> '
											  + call_details + '<div name="contact_numbers_placeholder"></div>' + view_contact
									  		  + '</div>', this.controller.window.document);
		
		itemNode.querySelector(".palm-row-wrapper").appendChild(element);
		
		this.loadContactNumbers(element, itemModel, is_valid);
		
		// no 'add to contact' or altnum row
		if ( ! is_valid && itemModel.contactId == -1 ) {
			element.querySelector('div[name="call-log-details-row"]').removeClassName('first').addClassName('single');
		}
		
		// event listener
		this.controller.listen(element, Mojo.Event.tap, this.drawerTapHandler.bindAsEventListener(this, itemModel));
		
		this.controller.instantiateChildWidgets(itemNode, itemModel);
	},
	
	loadContactNumbers: function(drawer, itemModel, is_valid) {
		var placeholder = drawer.querySelector('div[name="contact_numbers_placeholder"]');
		var populate = function(numbers) {
			placeholder.innerHTML = Mojo.View.render({template: 'calllog/listitem_altnums', collection: numbers});
		};
		
		// CASE: we have the contact
		if ( itemModel.contactId != -1 ) {
			var contactNumbers = this.contactNumberCache.get(itemModel.contactId);
			if ( contactNumbers === undefined ) {
				// 'Loading' row
				placeholder.innerHTML = Mojo.View.render({template: 'calllog/listitem_altnums_loading'});
				
				this.loadContactNumbersFromService(itemModel.contactId, function(contactNumbers) {
					this.contactNumberCache.set(itemModel.contactId, contactNumbers);
					populate(contactNumbers);
				}.bind(this));
			} else {
				populate(contactNumbers);
			}
			
		// CASE: unknown but valid number
		} else if ( is_valid ) {
			populate([{
				displayNumber: itemModel.displayNumber,
				label: '',
				details_json: Object.toJSON({
					number: TelephonyCommands.normalizeNumber(itemModel.number),
					label: ''
				})
			}]);
		}
	},
	
	loadContactNumbersFromService: function(contactId, callback) {
		this.controller.serviceRequest('palm://com.palm.contacts', {
			method: 'details',
			parameters: {'id': contactId },
			onSuccess: function(response) {
				var numbers = [];
				if ( response.record && response.record.phoneNumbers && response.record.phoneNumbers.length > 0 ) {
					numbers = response.record.phoneNumbers.collect(function(item) {
						var label = (Messages.phoneLabel[item.label] || '');
						return {
							displayNumber: Mojo.Format.formatPhoneNumber(item.value),
							displayLabel: label,
							// pass information to event by json enconding it in an HTML attribute
							// this will work as long as labels don't contain quotes
							details_json: Object.toJSON({
								number: TelephonyCommands.normalizeNumber(item.value),
								label: label,
								contactPointId: item.id
							})
						};
					});
				}
				callback(numbers);
			},
			onFailure: function(e) {
				Mojo.Log.error("Error loading contacts for contact id %s: %j",contactId,e);
				callback([]);
			}
		});
	},
	
	// opens drawer
	openDrawer: function( row_element, model, list_element ) {
		this.addDrawerToItem(row_element, model);
		model.open = true;
		row_element.addClassName('open');
		this.currentlyOpenDrawer = {
			model: model,
			element: row_element,
			list: list_element
		};
		
		// workaround for NOV-80346
		row_element._ignoreSwipeToDelete = true;
	},
	
	// closes currently open drawer
	closeDrawer: function() {
		// a drawer is open, now close it
		if ( this.currentlyOpenDrawer ) {
			this.currentlyOpenDrawer.model.open = false;
			
			// widgetAssistant code a workaround for NOV-88284
			var widgetAssistant = this.currentlyOpenDrawer.element.querySelector('div[name="rowdrawer"]')._mojoController.assistant;
			var originalScrollIntoView = widgetAssistant.scrollIntoView;
			widgetAssistant.scrollIntoView = Mojo.doNothing;
			this.controller.modelChanged(this.currentlyOpenDrawer.model);
			widgetAssistant.scrollIntoView = originalScrollIntoView;
			
			this.currentlyOpenDrawer.element.removeClassName('open');
			
			// workaround for NOV-80346
			this.currentlyOpenDrawer.element._ignoreSwipeToDelete = false;
			
			this.currentlyOpenDrawer = undefined;
		}
	},
	
	drawerTapHandler: function(event, itemModel) {
		var target = event.target, name, is_sms = false, is_ipdial = false;
		Event.stop(event);
		
		while ( target && (name = target.getAttribute("name")) != "rowdrawer" ) {
			switch (name) {
				case "sms":
					is_sms = true;
					break;
			  
			  //*************Sam, patch start for IP dial************
				case "ipdial":
				  is_ipdial = true;
				  break;
				//*************Sam, patch end for IP dial  ************
					
				case "number":
					var details = target.getAttribute('json').evalJSON();
					if ( is_sms ) {
						TelephonyCommands.messagingLaunch(itemModel.displayNumber, itemModel.contactId, details.contactPointId);
					} else {
						var numberstr = details.number;
						//*************Sam, patch start for IP dial************
						if (is_ipdial) {
					    numberstr = "wp" + numberstr;
						}
						//*************Sam, patch end for IP dial  ************
						this.dialNumber(numberstr, itemModel.contactId, details.label);
					}
					return;
					
				case "contact":
					if ( target.getAttribute('value') == -1 ) {
						TelephonyCommands.contactsLaunchWithPseudocard(target.getAttribute('number'));
					} else {
						TelephonyCommands.contactsLaunchWithId(target.getAttribute('value'));
					}
					return;
			}
			target = target.parentNode;
		}
	},
	
	isValidDialKey: function(key) {
		var i;
        for (i = 0; i < key.length; i++) {
			if (!((key[i] >= '0' && key[i] <= '9') 
				|| key[i] == '*' || key[i] == '#'
				|| key[i] == 'w' || key[i] == 'p' 
				|| key[i] == '+')) {
	            
				return false;
			}
		}
        return true;
    },
 	
    calllogQuery: function(listWidget, offset, count) {
		// workaround for NOV-89951
 		if (this.ignoreRequests) {
	        return;
	    }
       	CallLogList.logQuery(offset, count, "", this.callLogListWidget.mojo.noticeUpdatedItems, this.callLogListWidget.mojo.setLength);
    },
	
    calllogQueryMissed: function(listWidget, offset, count){
		// workaround for NOV-89951
 		if (this.ignoreRequests) {
	        return;
	    }
       	CallLogList.logQuery(offset, count, "missed", this.callLogListWidgetMissed.mojo.noticeUpdatedItems, this.callLogListWidgetMissed.mojo.setLength);
    },
	
	// update voicemail badge
	voicemailBadgeUpdate: function(count) {
		if (count > 0) {
			if (count == this.announcer.kUnknownVoicemailCount) {
				count = Messages.newVoicemailUnknownCount;
			}
			this.controller.get('voicemail_badge').removeClassName('hidden');
			this.controller.get('voicemail_count').textContent = count;
		} else {
			this.controller.get('voicemail_badge').addClassName('hidden');
		}
	},

	onVoicemailClick: function(event) {
		this.appAssistant.launchVoicemail();
	}

});

var ClearcalllogDialogAssistant = Class.create({
	
	initialize: function(sceneAssistant, listwidget) {
		this.sceneAssistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
	},
	
	setup : function(widget) {
		this.widget = widget;
		this.controller.get('okButton').addEventListener(Mojo.Event.tap, this.handleOK.bindAsEventListener(this));
		this.controller.get('cancel').addEventListener(Mojo.Event.tap, this.handleCancel.bindAsEventListener(this));
	},
	
	handleOK: function() {
		//clear all log
		CallLogList.deleteAll(function() {
			this.sceneAssistant.handleClear();
		}.bind(this), this.controller);
		this.widget.mojo.close();
	},
	
	handleCancel: function(){
		this.widget.mojo.close();
	}
});
